package top.tagao.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.tagao.entity.News;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@WebServlet("/newsListServlet")
public class NewsListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        //resp.getWriter().write("<h1>新闻列表</h1>");
        String type = req.getParameter("type");
        String name = req.getParameter("name");

        System.out.println(type + " " + name);

        List<News> newsList = new ArrayList<News> ();

        for (int i = 0; i < 3; i++){
            News news = new News("新闻标题00" + i, "seehope", "2021-02-25", "...");
            newsList.add(news);
        }

        // 把 newsList 对象转换为JSON 字符串
        String jsonString = JSON.toJSONString(newsList);
        // 返回数据
       // resp.getWriter().println(jsonString);

        HashMap<String, String> objectObjectHashMap = new HashMap<String,String>();
        objectObjectHashMap.put("ru01","01");
        objectObjectHashMap.put("ru02","02");
        String s = JSON.toJSONString(objectObjectHashMap);
        //resp.getWriter().write(s);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("newList",newsList);
        jsonObject.put("map",objectObjectHashMap);
        String s1 = jsonObject.toJSONString();
        resp.getWriter().write(s1);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
